package zh.demo.webuser.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zh.demo.commons.exception.RRException;
import zh.demo.commons.utils.*;
import zh.demo.commons.validator.Assert;
import zh.demo.webuser.annotation.AuthIgnore;
import zh.demo.webuser.annotation.LoginUser;
import zh.demo.webuser.model.UserEntity;
import zh.demo.webuser.model.WechatArticleCollectEntity;
import zh.demo.webuser.service.TokenService;
import zh.demo.webuser.service.WebUserService;
import zh.demo.webuser.service.WechatArticleCollectService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户
 * 
 * @author zhangheng
 * @email zh_123shmily@163.com
 * @date 2017-09-15 09:50:28
 */
@RestController
@RequestMapping("/api")
public class UserController {
	@Autowired
	private WebUserService userService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public static final String ROOT = "D:/upload/images";
	//用来存手机号验证码
	private Map<String, Object> codemap = new HashMap<>();

	private final ResourceLoader resourceLoader;

	@Autowired
	public UserController(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	/**
	 * 登录
	 */
	@AuthIgnore
	@PostMapping("/login")
	public R login(String mobile, String password){
		Assert.isBlank(mobile, "手机号不能为空");
		Assert.isBlank(password, "密码不能为空");

		//用户登录
		long userId = userService.login(mobile, password);

		//生成token
		Map<String, Object> map = tokenService.createToken(userId);
		map.put("userId", userId);
		return R.ok(map);
	}

	/**
	 * 注册
	 */
	@AuthIgnore
	@PostMapping("/register")
	public Map<String, Object> register(String mobile, String password,String smsCode){
		Assert.isBlank(mobile, "手机号不能为空");
		Assert.isBlank(password, "密码不能为空");
		String mcode = codemap.get(mobile).toString();
		//String mcode = stringRedisTemplate.opsForValue().get(mobile);
		Map<String, Object> map = new HashMap<String, Object>();
		if(!org.apache.commons.lang.StringUtils.isBlank(smsCode)){
			if(!smsCode.equals(mcode)) {
				map.put("code", 1);
				map.put("msg", "验证码错误");
				return map;
			}
		}
		userService.save(mobile, password);
		map.put("code",0);
		return map;
	}

	@AuthIgnore
	@RequestMapping("/newPassword")
	public Map<String, Object> updatePassword(String mobile, String password, String smsCode){
		Assert.isBlank(mobile, "手机号不能为空");
		Assert.isBlank(password, "密码不能为空");
		String mcode = codemap.get(mobile).toString();
		//String mcode = stringRedisTemplate.opsForValue().get(mobile);
		Map<String, Object> map = new HashMap<String, Object>();
		if(!org.apache.commons.lang.StringUtils.isBlank(smsCode)){
			if(!smsCode.equals(mcode)) {
				map.put("code", 1);
				map.put("msg", "验证码错误");
				return map;
			}
		}
		UserEntity user = userService.queryByMobile(mobile);
		user.setPassword(DigestUtils.sha256Hex(password));
		userService.update(user);
		map.put("code",0);
		return map;
	}

	@AuthIgnore
	@RequestMapping("/thirdPartAccountRegister")
	public R thirdPartAccountRegister(String account, String type){
		userService.thirdPartAccountRegister(account, type);
		return R.ok();
	}

	@AuthIgnore
	@RequestMapping("/thirdPartAccountLogin")
	public R thirdPartAccountLogin(String account, String type){
		UserEntity user = userService.thirdPartAccountLogin(account, type);
		if(user == null){
			return R.error("账号不存在,请联系管理员");
		}
		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		Map<String, Object> map = tokenService.createToken(user.getUserId());
		return R.ok().put("r",map);
	}

	/**
	 * 获取手机短信验证码
	 * @param mobile
	 * @return
	 */
	@AuthIgnore
	@PostMapping("/getCode")
	public R getCode(String mobile){
		Map<String, String> para = new HashMap<String, String>();

		/**
		 * 目标手机号码，多个以“,”分隔，一次性调用最多100个号码，示例：139********,138********
		 */
		para.put("mob", mobile);

		/**
		 * 微米账号的接口UID
		 */
		para.put("uid", "QuSugydhxPUe");

		/**
		 * 微米账号的接口密码
		 */
		para.put("pas", "h45knk4p");

		/**
		 * 接口返回类型：json、xml、txt。默认值为txt
		 */
		para.put("type", "json");

		/**
		 * 短信内容。必须设置好短信签名，签名规范：

		 * 1、短信内容一定要带签名，签名放在短信内容的最前面；

		 * 2、签名格式：【***】，签名内容为三个汉字以上（包括三个）；

		 * 3、短信内容不允许双签名，即短信内容里只有一个“【】”
		 *
		 */
		para.put("cid", "fG63vomkfYWT");

		String code = RandomUtils.generaterNumber(6);
		para.put("p1", code);
//        para.put("p2", "3");
		/**
		 * 特别注意：参数传递时去除“<>”符号！
		 */
		try {
			System.out.println(HttpClientHelper.convertStreamToString(
					HttpClientHelper.get("http://api.weimi.cc/2/sms/send.html",
							para), "UTF-8"));

            /*System.out.println(HttpClientHelper.convertStreamToString(
                    HttpClientHelper.post(
                            "http://api.weimi.cc/2/sms/send.html", para),
                    "UTF-8"));*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		codemap.put(mobile, code);
		//stringRedisTemplate.opsForValue().set(mobile,code);
		return R.ok().put("SmsCode", code);
	}

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("user:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<UserEntity> userList = userService.queryList(query);
		int total = userService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}

	/**
	 * 获得登录用户的信息
	 */
	@PostMapping("/userInfo")
	public R info(@LoginUser UserEntity user){
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存
	 */
	@AuthIgnore
	@RequestMapping("/save")
	public R save(@RequestBody UserEntity user){
		userService.save(user);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@PostMapping("/update")
	public R update(@LoginUser UserEntity user,@RequestBody UserEntity userInfo){
		userInfo.setUserId(user.getUserId());
		userService.update(userInfo);
		
		return R.ok();
	}

	@AuthIgnore
	@PostMapping("/updateUser")
	public R updateUser(@RequestBody UserEntity userInfo){
		userService.update(userInfo);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@AuthIgnore
	@RequestMapping("/delete")
	//@RequiresPermissions("user:delete")
	public R delete(@RequestBody Long[] userIds){
		userService.deleteBatch(userIds);
		
		return R.ok();
	}

	/**
	 * 上传身份证照片
	 *
	 * @param file
	 * @param request
	 * @return
	 */
	@AuthIgnore
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST, headers = {"Content-Type=multipart/form-data"})
	public R test(@RequestBody MultipartFile file, HttpServletRequest request, @LoginUser UserEntity userEntity, String type) {

		String filePath = "";
		String filename = "";
		// 判断文件是否为空
		if (!file.isEmpty()) {
			if (file.getSize() > 10240000) {
				throw new RRException("上传失败：文件大小不能超过10M");
			}
			try {
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

				Long userId = userEntity.getUserId();
				UserEntity user = userService.queryObject(userId);
				if(user!=null){
					if("0".equals(type)){
						filename = userId+"_face_" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + postfix;
						user.setImagePath(filename);
					}else{ //除了身份证以外的上传图片
						filename = userId+"_bl_" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + postfix;
						user.setBusinessLicence(filename);
					}
					userService.save(user);
				}else{
					return R.error().put("msg","用户不存在");
				}
				// 文件保存路径

				filePath = "D:/upload/face/"+ filename;
				File saveDir = new File(filePath);

				//判断目标文件所在的目录是否存在
				if (!saveDir.getParentFile().exists()) {
					//如果目标文件所在的目录不存在，则创建父目录
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			throw new RRException("上传失败:请添加上传文件！");
		}
		System.out.println("filePath:" + filePath);

		return R.ok().put("url", filePath);//.put("fileId",ossEntity.getId());
	}

	@AuthIgnore
	@RequestMapping(value = "/info/{id}")
	public R getUserById(@PathVariable("id") Long id){
		UserEntity user = userService.queryObject(id);
		return R.ok().put("user",user);
	}


}
